package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import util.bean.ResultSetProcessor;

import bean.User;

import static util.DatabaseForMySQLUtil.*;

public class UserDAO {
	private final static UserDAO INSTANCE = new UserDAO();

	private UserDAO() {}

	public static UserDAO getInstance() {
		return INSTANCE;
	}

	public int delUser(User user) {
		String sql = "delete from users where id = " + user.getId();
		return executeUpdate(sql);
	}

	public User findUserById(Long id) {
		String sql = "select id,username,email,password from users where id = ?";

		return (User) query(sql, new ResultSetProcessor() {
			public Object exec(ResultSet rs) throws SQLException {
				User user = null;
				if (rs.next()) {
					user = new User();

					user.setId(rs.getLong("id"));
					user.setEmail(rs.getString("email"));
					user.setPassword(rs.getString("password"));
					user.setUsername(rs.getString("username"));
					user.setRoles(RoleDAO.getInstance().getRoles(user.getId()));
				}
				return user;
			}
		}, id);
	}

	public User findUserByName(String userName) {
		String sql = "select id,username,email,password from users where username = ?";

		return (User) query(sql, new ResultSetProcessor() {
			public Object exec(ResultSet rs) throws SQLException {
				User user = null;
				if (rs.next()) {
					user = new User();

					user.setId(rs.getLong("id"));
					user.setEmail(rs.getString("email"));
					user.setPassword(rs.getString("password"));
					user.setUsername(rs.getString("username"));
					user.setRoles(RoleDAO.getInstance().getRoles(user.getId()));
				}
				return user;
			}
		}, userName);
	}

	public void addUser(User user) {
		Connection connection = null;
		PreparedStatement statement = null;

		try {
			String sql = "insert into users(username,email,password) values(?,?,?)";

			connection = getConnection();
			statement = connection.prepareStatement(sql);

			statement.setString(1, user.getUsername());
			statement.setString(2, user.getEmail());
			statement.setString(3, user.getPassword());

			statement.executeUpdate();

			user.setId(getLastInsertId());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			close(connection, statement);
		}
	}

	public static void main(String[] args) {
	}

}
